package com.itcast.homework05.work11;

import java.util.Scanner;

/*
已知一个从小到大排好顺序的整数数组, 请键盘录入一个整数,
查询这个整数在数组中出现的索引位置,要求:
(1) 编写方法完成, 将查到的索引返回
(2) 使用二分找出思想完成
*/
public class Test {
    public static void main(String[] args) {
        int[] arr = {12, 13, 14, 15, 23, 26, 35};
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要查找的数");
        int i = sc.nextInt();
        int resout = ResoutId(arr, i);
        if (resout == -1) {
            System.out.println(i + "在数组中不存在！");
        } else {
            System.out.println(i + "在数组中的索引位置为：" + resout);
        }
    }

    public static int ResoutId(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int middle = (right + left) / 2;
            if (arr[middle] > target) {
                right = middle - 1;
            } else if (arr[middle] < target) {
                left = middle + 1;
            } else {
                return middle;
            }
        }
        return -1;
    }
}
